<template>
  <div class="app-container">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="快递编码">
        <el-input v-model="billNum" placeholder="快递编码"></el-input>
      </el-form-item>
      <el-form-item label="快递公司">
        <el-input v-model="courierCompany" placeholder="快递公司"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchInfo()">查询</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="dialogAddVisible = true">新增</el-button>

    <el-button type="danger" @click="deleteInfoBatch()">批量删除</el-button>
    <!-- :data 绑定页面显示的数据的列表
        prop 绑定的数据的名称
        -->
    <el-table :data="list" v-loading="listLoading" element-loading-text="Loading" stripe style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="billNum" label="快递编码" width="180">
      </el-table-column>
      <el-table-column prop="courierCompany" label="快递公司" width="180">
      </el-table-column>
      <el-table-column prop="expressAddress" label="收货地址">
      </el-table-column>
      <el-table-column prop="recipient" label="收货人昵称"> </el-table-column>
      <el-table-column prop="phone" label="收货人电话"> </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <!-- 判断 status 的值并显示不同的内容 -->
          <span v-if="scope.row.status === 0">未到达</span>
          <span v-if="scope.row.status === 1">已到达</span>
          <span v-if="scope.row.status === 2">代取中</span>
          <span v-if="scope.row.status === 3">待支付</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220" align="center">
        <template slot-scope="scope">
          <!-- 状态3显示支付按钮 -->
          <el-button v-if="scope.row.status === 3" size="mini" type="success"
            @click="handlePayment(scope.index, scope.row)">
            去支付
          </el-button>

          <!-- 非状态3显示代取按钮 -->
          <el-button v-else size="mini" type="primary" :disabled="scope.row.status !== 1"
            @click="handlePickup(scope.index, scope.row)">
            代取
          </el-button>

          <!-- 通用删除按钮 -->
          <el-button size="mini" type="danger" @click="handleDelete(scope.index, scope.row)" style="margin-left: 8px">
            删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <el-dialog title="新增快递单" :visible.sync="dialogAddVisible" width="680px" custom-class="express-dialog">
      <el-form :model="form" label-position="top" class="compact-form" ref="addForm">
        <el-row :gutter="20">
          <!-- 第一行 -->
          <el-col :span="12">
            <el-form-item label="快递编码" prop="billNum" class="highlight-item">
              <el-input v-model="form.billNum" placeholder="请输入12位数字编码" clearable maxlength="12"
                @blur="handleBlurBillNum">
                <i slot="prefix" class="el-icon-postcard"></i>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="快递公司">
              <el-input v-model="form.courierCompany" disabled class="disabled-input">
                <i slot="prefix" class="el-icon-truck"></i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="收货人">
              <el-input v-model="form.recipient" disabled class="disabled-input">
                <i slot="prefix" class="el-icon-user"></i>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input v-model="form.phone" disabled class="disabled-input">
                <i slot="prefix" class="el-icon-mobile-phone"></i>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="物流状态">
              <el-tag :type="statusTagType" class="status-tag">
                {{ statusText }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 地址行 -->
        <el-form-item label="收货地址">
          <el-input v-model="form.expressAddress" disabled class="disabled-input">
            <i slot="prefix" class="el-icon-location-outline"></i>
          </el-input>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注信息">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入特殊配送要求或备注" class="remark-input"
            maxlength="100" show-word-limit />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="beforeCancel" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="addInfo" class="confirm-btn" icon="el-icon-circle-check">
          添加
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="代取订单" :visible.sync="dialogSubstitutionVisible" width="720px" custom-class="substitution-dialog">
      <el-form :model="substitutionData" label-position="top" class="compact-form" ref="substitutionForm">
        <el-row :gutter="20">
          <!-- 左列 -->
          <el-col :span="12">
            <!-- 快递信息 -->
            <div class="info-block">
              <div class="block-header">📦 快递信息</div>
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="快递编码">
                    <el-input v-model="substitutionData.billNum" disabled>
                      <i slot="prefix" class="el-icon-document"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="快递公司">
                    <el-input v-model="substitutionData.courierCompany" disabled>
                      <i slot="prefix" class="el-icon-truck"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 收件人信息 -->
            <div class="info-block">
              <div class="block-header">👤 收件人信息</div>
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="收货人" prop="recipient">
                    <el-input v-model="substitutionData.recipient" placeholder="请输入姓名">
                      <i slot="prefix" class="el-icon-user"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系电话" prop="recipientPhone">
                    <el-input v-model="substitutionData.recipientPhone" placeholder="11位手机号" maxlength="11">
                      <i slot="prefix" class="el-icon-mobile-phone"></i>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>

          <!-- 右列 -->
          <el-col :span="12">
            <!-- 配送信息 -->
            <div class="info-block">
              <div class="block-header">🚚 配送设置</div>
              <el-form-item label="配送时间" required>
                <el-date-picker v-model="deliveryDate" type="date" placeholder="选择日期" :picker-options="dateOptions"
                  value-format="yyyy-MM-dd" style="width: 48%; margin-right: 4%"></el-date-picker>
                <el-time-select v-model="deliveryTime" :picker-options="timeOptions" placeholder="选择时间"
                  style="width: 48%"></el-time-select>
              </el-form-item>

              <el-form-item label="配送员" prop="deliveryPersonId">
                <el-select v-model="substitutionData.deliveryPersonId" placeholder="选择配送员"
                  @change="handleDeliveryPersonChange" class="delivery-select">
                  <el-option v-for="item in allDeliveryPersonInfo" :key="item.id" :label="item.username"
                    :value="item.id">
                    <div class="delivery-option">
                      <el-avatar :size="24"
                        :src="item.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
                      <span style="margin-left:10px">{{ item.username }}</span>
                      <span style="margin-left:auto; color:#999">{{ item.phone }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="支付方式" class="payment-methods">
                <el-radio-group v-model="substitutionData.payType" size="medium">
                  <el-radio-button label="1">
                    <i class="el-icon-wallet" style="color:#1677ff"></i>
                    <span>支付宝</span>
                  </el-radio-button>
                  <el-radio-button label="0">
                    <i class="el-icon-coin" style="color:#e6a23c"></i>
                    <span>积分支付</span>
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <!-- 地址备注 -->
        <div class="info-block">
          <div class="block-header">📍 地址信息</div>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="代取地址">
                <el-input v-model="substitutionData.pickupAddress" disabled>
                  <i slot="prefix" class="el-icon-location-outline"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="配送地址" prop="deliveryAddress">
                <el-input v-model="substitutionData.deliveryAddress" placeholder="请输入详细地址">
                  <i slot="prefix" class="el-icon-office-building"></i>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="订单备注">
            <el-input v-model="substitutionData.remark" type="textarea" :rows="2" placeholder="请输入特殊要求" maxlength="100"
              show-word-limit class="remark-input" />
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="beforeuSubstitutionCancel" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleSubmit" class="confirm-btn" icon="el-icon-sold-out">
          立即支付
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="ewmDialogVisible" width="320px" center custom-class="payment-dialog">
      <div class="payment-content">
        <!-- 支付方式标题 -->
        <div class="payment-header">
          <i class="el-icon-wallet" style="color: #1677ff; margin-right: 8px"></i>
          <h2 style="color: #1677ff; margin: 0">支付宝支付</h2>
        </div>

        <!-- 二维码区域 -->
        <div class="qrcode-container" v-show="!paySucc">
          <div class="qrcode-border">
            <vueQr :text="qr" :size="200" :margin="10" :correctLevel="3" :whiteMargin="false" colorDark="#1677ff"
              colorLight="#f0f7ff"></vueQr>
          </div>
          <p class="tip-text">请使用支付宝扫一扫完成支付</p>
        </div>

        <!-- 支付成功反馈 -->
        <div class="success-feedback" v-show="paySucc">
          <div class="success-icon">
            <i class="el-icon-success animated bounceIn"></i>
          </div>
          <div class="success-text">
            <p class="title">支付成功</p>
            <p class="subtitle">感谢您的使用</p>
          </div>
        </div>
      </div>
    </el-dialog>


    <!-- 选择支付方式弹窗 -->
    <el-dialog title="选择支付方式" :visible.sync="paymentDialogVisible" width="400px" :close-on-click-modal="false">
      <el-radio-group v-model="payType" class="horizontal-payment">
        <el-radio label="0" class="payment-option">
          <div class="payment-content">
            <span>支付宝支付</span>
          </div>
        </el-radio>
        <el-radio label="1" class="payment-option">
          <div class="payment-content">
            <span>积分支付</span>
          </div>
        </el-radio>
      </el-radio-group>

      <div slot="footer" class="dialog-footer">
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="payment()">确认支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPageExpressDelivery,
  deleteExDeBatch,
  addExDe,
  getExDeliveryInfo,
  deleteOneExDe,
  prePay,
  createOrder,
  checkTradeOrderStatus,
  tradePayCancel
} from "@/api/user/express";
import { getDeliveryPersonInfo } from "@/api/delivery/delivery";
import { getPoint } from "@/api/user";
import { getOneOrder, payByPoint } from "@/api/user/order";
import vueQr from "vue-qr";
import moment from 'moment';

export default {
  components: {
    vueQr,
  },

  data() {
    return {
      currentPage: 1,
      pageSize: 5,
      total: 100,
      billNum: "",
      courierCompany: "",
      list: [], // 分页查询返回的数据
      listLoading: true,
      isPaymentCompleted: false, // 支付完成标识
      dialogAddVisible: false, // 新增对话框是否显示
      dialogUpdateVisible: false, // 更新对话框是否显示
      dialogSubstitutionVisible: false, //代取的对话框是否显示
      paymentDialogVisible: false, //选择支付方式的弹窗
      payType: 1, //支付方式
      orderId: "", // 用于生成订单之后再次支付时
      // 新增对话框绑定的数据
      form: {
        billNum: "",
        courierCompany: "",
        recipient: "",
        phone: "",
        expressAddress: "",
        status: "",
        remark: "",
      },
      statusTagType: 'warning', // 根据状态动态设置：success/warning/danger等
      // 代取对话框绑定的数据
      substitutionData: {
        expressDeliveryId: "", // 快递的id
        billNum: "", //快递编号
        courierCompany: "", // 快递公司
        recipient: "", // 收货人
        recipientPhone: "",
        pickupAddress: "", // 代取地点
        deliveryTime: "", // 代取时间
        deliveryAddress: "", //配送地点
        remark: "",
        deliveryPersonId: "", //配送员id
        deliveryPersonPhone: "", //配送员电话，仅用于前端展示
        payType: 1, //支付方式
      },
      formLabelWidth: "140px",
      multipleSelection: [], // 多选的时候存储选择的数据的行id
      allDeliveryPersonInfo: [], //所有外卖员信息
      ewmDialogVisible: false, // 支付二维码弹窗
      qr: "", //二维码路径
      paySucc: false,
      deliveryDate: null,
      deliveryTime: null,
      dateOptions: {
        disabledDate: (time) => {
          const now = moment()
          const cutoffHour = 20 // 晚上8点
          const currentHour = now.hour()

          // 如果当前时间晚于20点，最早可选明天
          const minDate = currentHour >= cutoffHour
            ? now.clone().add(1, 'days').startOf('day')
            : now.clone().hour(cutoffHour).isAfter(now)
              ? now.clone().startOf('day')
              : now.clone().add(1, 'days').startOf('day')

          // 最大可选大后天
          const maxDate = now.clone().add(3, 'days').endOf('day')

          return time < minDate || time > maxDate
        }
      },
      timeOptions: {
        start: '08:00',
        end: '22:00',
        step: '00:30',
        minTime: this.getMinTime()
      },
      pollingCount: 0,     // 当前轮询次数
      maxPollingTimes: 10,  // 最大轮询次数
      pollingInterval: 2000, // 轮询间隔(ms)
      pollingTimer: null   // 定时器引用
    };
  },
  created() {
    this.fetchData();
  },
  computed: {
    statusText() {
      switch (this.form.status) {
        case 0:
          return "未到达";
        case 1:
          return "已到达";
        case 2:
          return "已完成";
        default:
          return "";
      }
    },
    // 监听日期和时间变化组合成最终值
    substitutionData: {
      get() {
        return this.value
      },
      set(val) {
        if (this.deliveryDate && this.deliveryTime) {
          val.deliveryTime = moment(`${this.deliveryDate} ${this.deliveryTime}`).format('YYYY-MM-DD HH:mm:ss')
        }
        this.$emit('input', val)
      }
    }
  },

  watch: {
    deliveryDate(newVal) {
      this.timeOptions.minTime = this.getMinTime()
    },
    'deliveryDate': {
      handler(newVal) {
        this.handleDateTimeChange(newVal, this.deliveryTime)
      }
    },
    'deliveryTime': {
      handler(newVal) {
        this.handleDateTimeChange(this.deliveryDate, newVal)
      }
    }
  },
  methods: {
    handleDateTimeChange(date, time) {
      if (date && time) {
        // 使用moment处理时间拼接
        const combined = moment(`${date} ${time}`).format('YYYY-MM-DD HH:mm:ss')

        // 如果需要严格校验时间有效性
        if (!moment(combined).isValid()) {
          console.error('无效的时间组合')
          return
        }

        // 更新到目标字段
        this.substitutionData.deliveryTime = combined

        // 如果直接需要修改原字段（根据业务需求）
        // this.substitutionData.deliveryTime = combined
      } else {
        // 清空逻辑（可选）
        this.substitutionData.deliveryTime = null
      }
    },
    getMinTime() {
      if (!this.deliveryDate) return '08:00'
      const isToday = moment(this.deliveryDate).isSame(moment(), 'day')
      if (!isToday) return '08:00'

      const now = moment()
      const currentMinutes = now.minutes()
      let nextHour = now.hour()

      // 计算最近的可选时间点
      if (currentMinutes > 30) {
        nextHour += 1
        return `${nextHour.toString().padStart(2, '0')}:00`
      } else {
        return `${nextHour.toString().padStart(2, '0')}:${currentMinutes < 30 ? '30' : '00'}`
      }
    },
    handleSubmit() {
      this.$refs.substitutionForm.validate(valid => {
        if (valid) {
          if (!this.substitutionData.deliveryTime) {
            this.$message.warning('请选择配送时间')
            return
          }
          this.toPayment()
        }
      })
    },
    fetchData() {
      this.listLoading = true;
      console.log(this.currentPage);
      getPageExpressDelivery({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        billNum: this.billNum,
        courierCompany: this.courierCompany,
      }).then((response) => {
        this.list = response.data.dataList;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },

    searchInfo() {
      this.fetchData();
    },

    handleDelete(index, row) {
      console.log(index, row);
      deleteOneExDe({ id: row.id }).then((res) => {
        // 重写获取列表
        this.fetchData();
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.fetchData();
    },

    // 处理通过复选框选中的数据
    handleSelectionChange(val) {
      this.multipleSelection = [];
      // val是选中的行的数据组成的数组
      for (var i = 0; i < val.length; i++) {
        // 将选中的id存入数组
        this.multipleSelection.push(val[i].id);
      }
      // console.log(this.multipleSelection)
    },
    deleteInfoBatch() {
      deleteExDeBatch(this.multipleSelection).then((res) => {
        if (res.code == 200) {
          this.fetchData();
        } else {
          alert(res.msg);
        }
      });
    },
    addInfo() {
      addExDe(this.form).then((res) => {
        if (res.code == 200) {
          this.dialogAddVisible = false;
          this.form = {
            billNum: "",
            courierCompany: "",
            recipient: "",
            phone: "",
            expressAddress: "",
            status: "",
            remark: "",
          };
          this.fetchData();
        } else {
          alert(res.msg);
        }
      });
    },
    handleBlurBillNum() {
      if (!this.form.billNum) {
        this.$message.error("请输入快递编码");
        return;
      }
      getExDeliveryInfo({ billNum: this.form.billNum }).then((res) => {
        if (res.code == 200) {
          this.form = res.data;
        } else {
          alert(res.msg);
        }
      });
    },
    beforeCancel() {
      this.dialogAddVisible = false;
      this.form = {
        billNum: "",
        courierCompany: "",
        recipient: "",
        phone: "",
        expressAddress: "",
        status: "",
        remark: "",
      };
    },
    handlePayment(index, row) {
      this.paymentDialogVisible = true
      // 根据快递编码获取订单id
      getOneOrder({
        expressDeliveryId: row.id
      }).then(res => {
        if (res.code == 200) {
          this.orderId = res.data.id
        }
      })
    },
    payment() {
      console.log(this.payType)
      if (this.payType != 1 && this.payType != 0) {
        this.$message({
          message: "请选择支付方式",
          type: "warning",
        });
      } else {
        if (this.payType == 1) {
          // 积分支付
          getPoint().then(async (res) => {
            if (res.code == 200) {
              if (res.data < 10) {
                this.$message({
                  message: "你的积分不足10分",
                  type: "warning",
                });
              } else {
                // 积分足够的话，创建订单并扣除积分
                await this.$confirm('确定要使用积分支付吗', '提示', { type: 'warning' })
                payByPoint({ orderId: this.orderId }).then(res => {
                  if (res.code == 200) {
                    this.$message({
                      message: "支付成功",
                      type: "success",
                    });
                    this.fetchData()
                  }
                })
              }
            }
          });

        } else {
          // 支付宝支付
          prePay({
            // 传给后端的订单id是要让后端查数据库获取订单的信息
            orderId: this.orderId,
            payType: this.payType,
          }).then((res) => {
            if (res.code == 200) {
              this.qr = res.data.qrCodeUrl;
              this.isPaymentCompleted = false; // 重置支付状态
              // this.orderNo = res.data.orderNo;
              console.log(this.qr);
              // 判断浏览器端是否支持websocket
              if ("WebSocket" in window) {
                // 创建 websocket对象
                // 通道地址按照项目进行配置
                var ws = new WebSocket("ws://localhost:8080/bindingRecord");
                // 建立连接时触发的事件
                ws.onopen = function () {
                  console.log("建立连接");
                  // Web Socket 已连接上，使用 send() 方法发送数据
                  // ws.send("data");
                  // console.log("数据发送中...");
                };
                // 收到服务端消息时触发的事件
                ws.onmessage = function (evt) {
                  // 接收后台推送的数据
                  console.log("接收数据：" + evt.data);
                  if (Boolean(evt.data)) {
                    _this.paySucc = true;
                    clearTimeout(_this.pollingTimer);
                    console.log("关闭二维码");
                    _this.isPaymentCompleted = true;
                    // 间隔3秒后，隐藏二维码的显示
                    setTimeout(() => {
                      _this.ewmDialogVisible = false;
                    }, 3 * 1000);
                  }
                  ws.close();
                };
                // 连接关闭时触发的事件
                ws.onclose = function () {
                  console.log("连接关闭");
                };
              } else {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
              }
              this.ewmDialogVisible = true;
              this.fetchData()
              // 轮询交易订单的状态
              // 通过轮询，如果长时间交易订单都不是支付完成的状态，说明客户可能中断支付，关闭交易订单，结束轮序
              // 支付成功，回调失败，通过轮询如果发现交易订单已经支付成功，进行后续修改数据库等处理，结束轮询
              this.startPaymentPolling(this.orderId);
            }
          });
        }
      }
    },
    // 点击代取按钮触发的函数
    handlePickup(index, row) {
      console.log(row)
      this.dialogSubstitutionVisible = true;
      this.substitutionData = row;
      this.substitutionData.expressDeliveryId = row.id;
      this.substitutionData.pickupAddress = row.expressAddress;
      // 调用接口获取配送员信息
      getDeliveryPersonInfo().then((res) => {
        if (res.code == 200) {
          this.allDeliveryPersonInfo = res.data;
        } else {
          alert(res.msg);
        }
      });
    },
    beforeuSubstitutionCancel() {
      this.form = {
        billNum: "",
        courierCompany: "",
        recipient: "",
        phone: "",
        expressAddress: "",
        status: "",
        remark: "",
      };
      this.dialogSubstitutionVisible = false;
      this.fetchData();
      // 取消后需生成一个持续半个小时的订单
    },
    addSubstitutionInfo() {
      this.dialogSubstitutionVisible = false;
    },
    // 选择完配送员，填充配送员电话
    handleDeliveryPersonChange() {
      const selectedPerson = this.allDeliveryPersonInfo.find(
        (person) => person.id === this.substitutionData.deliveryPersonId
      );
      if (selectedPerson) {
        this.substitutionData.deliveryPersonPhone = selectedPerson.phone;
      }
    },
    // 支付
    toPayment() {
      let _this = this;
      // 先判断有没有选配送员
      if (!this.substitutionData.deliveryPersonId) {
        this.$message.error("请选择配送员");
        return;
      }
      // 判断：如果是积分支付，先发请求获取用户的积分是否足够支付，如果够了，再去创建订单
      //      如果是支付宝支付，直接创建订单并调取接口获取二维码
      if (this.substitutionData.payType == 0) {
        getPoint().then(async (res) => {
          if (res.code == 200) {
            if (res.data < 10) {
              this.$message({
                message: "你的积分不足10分",
                type: "warning",
              });
            } else {
              // 积分足够的话，创建订单并扣除积分
              await this.$confirm('确定要使用积分支付吗', '提示', { type: 'warning' })
              createOrder(this.substitutionData).then((res) => {
                if (res.code == 200) {
                  this.$message({
                    message: "支付成功",
                    type: "success",
                  });
                }
              });
            }
          }
        });
      } else {
        // 否则就是支付宝支付
        // 这里需要先根据订单数据生成后端订单，如果取消支付的话，订单设置定时任务持续30分钟
        createOrder(this.substitutionData).then((res) => {
          if (res.code == 200) {
            // 返回业务订单的id
            this.orderId = res.data;
            // 创建成功业务订单之后，调起支付操作
            // 这里填写后台支付的地址
            prePay({
              // 传给后端的订单id是要让后端查数据库获取订单的信息
              orderId: this.orderId,
              payType: this.substitutionData.payType,
            }).then((res) => {
              if (res.code == 200) {
                this.qr = res.data.qrCodeUrl;
                this.isPaymentCompleted = false; // 重置支付状态
                // this.orderNo = res.data.orderNo;
                console.log(this.qr);
                // 判断浏览器端是否支持websocket
                if ("WebSocket" in window) {
                  // 创建 websocket对象
                  // 通道地址按照项目进行配置
                  var ws = new WebSocket("ws://localhost:8080/bindingRecord");
                  // 建立连接时触发的事件
                  ws.onopen = function () {
                    console.log("建立连接");
                    // Web Socket 已连接上，使用 send() 方法发送数据
                    // ws.send("data");
                    // console.log("数据发送中...");
                  };
                  // 收到服务端消息时触发的事件
                  ws.onmessage = function (evt) {
                    // 接收后台推送的数据
                    console.log("接收数据：" + evt.data);
                    if (Boolean(evt.data)) {
                      _this.paySucc = true;
                      _this.isPaymentCompleted = true;
                      console.log("关闭二维码");
                      // 间隔3秒后，隐藏二维码的显示
                      // 终止轮询定时器
                      clearTimeout(_this.pollingTimer);
                      setTimeout(() => {
                        _this.ewmDialogVisible = false;
                      }, 3 * 1000);
                    }
                    ws.close();
                  };
                  // 连接关闭时触发的事件
                  ws.onclose = function () {
                    console.log("连接关闭");
                  };
                } else {
                  // 浏览器不支持 WebSocket
                  alert("您的浏览器不支持 WebSocket!");
                }
                this.ewmDialogVisible = true;
                // 轮询交易订单的状态
                // 通过轮询，如果长时间交易订单都不是支付完成的状态，说明客户可能中断支付，关闭交易订单，结束轮序
                // 支付成功，回调失败，通过轮询如果发现交易订单已经支付成功，进行后续修改数据库等处理，结束轮询
                this.startPaymentPolling(this.orderId);
              }
            });
          }
        });
      }
      // 刷新界面
      this.fetchData();
    },
    // 轮询方法
    startPaymentPolling(orderId) {
      this.pollingCount = 0;
      this.maxPollingTimes = 10;
      this.pollingInterval = 2000;
      this.pollingTimer = null;

      const poll = async () => {
        if (this.isPaymentCompleted || this.pollingCount >= this.maxPollingTimes) {
          if (!this.isPaymentCompleted) {
            this.handlePaymentTimeout(orderId);
          }
          return;
        }

        try {
          this.pollingCount++;
          const res = await checkTradeOrderStatus({ orderId });

          if (res.code === 200) {
            if (res.data == 4 || res.data == 0) {
              this.pollingTimer = setTimeout(poll, this.pollingInterval);
            }else if (res.data == 2){
              // 交易关闭，关闭二维码
              this.$message({
                    message: "交易关闭",
                    type: "warning",
                  });
              this.ewmDialogVisible = false
            } else {
              this.isPaymentCompleted = true;
              clearTimeout(this.pollingTimer);
            }
          } 
        } catch (error) {
          this.pollingTimer = setTimeout(poll, this.pollingInterval);
        }
      };

      poll();
    },
    // 支付成功处理
    handlePaymentSuccess(data) {
      console.log('支付成功，订单数据:', data);
      this.isPaymentCompleted = true;
    },

    // 支付超时处理
    handlePaymentTimeout(orderId) {
      console.warn('支付超时，关闭交易');
      // 支付超时的话需要关闭订单
      tradePayCancel({orderId : orderId}).then(res => {
        if(res.code == 200){
          if(res.data == 1){
            this.$message({
                    message: "订单支付超时，请重新发起支付",
                    type: "warning",
                  });
          } else if (res.data == 0){
            this.$message({
                    message: "支付宝沙箱环境出问题了，请稍后再试",
                    type: "warning",
                  });
          }
        }else {
          this.$message({
                    message: "支付宝沙箱环境出问题了，请稍后再试",
                    type: "error",
                  });
        }
      })
      this.ewmDialogVisible = false;
      this.fetchData()
    },
    // 组件销毁时清理
    beforeDestroy() {
      if (this.pollingTimer) {
        clearTimeout(this.pollingTimer);
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.payment-dialog {
  .payment-content {
    text-align: center;

    .payment-header {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 18px;

      h2 {
        font-size: 20px;
        font-weight: 600;
      }
    }

    .qrcode-container {
      .qrcode-border {
        padding: 12px;
        background: #f0f7ff;
        border-radius: 12px;
        display: inline-block;
        box-shadow: 0 4px 12px rgba(22, 119, 255, 0.1);
      }

      .tip-text {
        color: #666;
        font-size: 13px;
        margin: 15px 0;
      }
    }

    .success-feedback {
      padding: 20px 0;

      .success-icon {
        i {
          font-size: 80px;
          color: #67c23a;
          background: #ffffff;
          border-radius: 50%;
          box-shadow: 0 4px 16px rgba(103, 194, 58, 0.2);
        }
      }

      .success-text {
        margin-top: 15px;

        .title {
          font-size: 18px;
          color: #333;
          margin: 0;
          font-weight: 600;
        }

        .subtitle {
          color: #999;
          font-size: 13px;
          margin: 5px 0 0;
        }
      }
    }
  }

  ::v-deep .el-dialog__header {
    border-bottom: 1px solid #eee;
  }
}

.animated {
  animation-duration: 0.6s;
}

@keyframes bounceIn {
  from {
    transform: scale(0.8);
    opacity: 0;
  }

  to {
    transform: scale(1);
    opacity: 1;
  }
}

.express-dialog {
  .compact-form {
    .el-row {
      margin-bottom: 12px;
    }

    .highlight-item {
      .el-input__inner {
        border-color: #409EFF;
        background: #f5f9ff;
      }
    }

    .disabled-input {
      ::v-deep .el-input__inner {
        background-color: #f8f9fa;
        color: #606266;
        cursor: not-allowed;
      }
    }

    .status-tag {
      width: 100%;
      text-align: center;
      padding: 12px 0;
      font-size: 14px;
      border-radius: 4px;
    }

    .remark-input {
      ::v-deep .el-textarea__inner {
        border-radius: 6px;
        background: #fcfcfc;

        &:focus {
          border-color: #409EFF;
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
        }
      }
    }
  }

  .dialog-footer {
    margin-top: 20px;

    .cancel-btn {
      padding: 10px 24px;

      &:hover {
        color: #409EFF;
        border-color: #c6e2ff;
        background: #ecf5ff;
      }
    }

    .confirm-btn {
      padding: 10px 24px;
      background: #409EFF;
      border-radius: 4px;

      &:hover {
        background: #66b1ff;
      }
    }
  }

  [class^="el-icon-"] {
    color: #909399;
    margin-right: 8px;
  }
}

.substitution-dialog {
  .compact-form {
    .info-block {
      margin-bottom: 20px;
      padding: 15px;
      background: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #eee;

      .block-header {
        font-size: 15px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 15px;
        padding-bottom: 8px;
        border-bottom: 2px solid #eaeefb;
      }
    }

    .delivery-select {
      width: 100%;

      ::v-deep .el-select-dropdown__item {
        height: auto;
        padding: 8px 15px;
      }
    }

    .delivery-option {
      display: flex;
      align-items: center;
      width: 100%;
    }

    .payment-methods {
      ::v-deep .el-radio-button {
        margin-right: 10px;

        &__inner {
          display: flex;
          align-items: center;
          padding: 10px 15px;

          i {
            margin-right: 5px;
          }
        }
      }
    }

    .remark-input {
      ::v-deep .el-textarea__inner {
        background: #fdfdfd;
        border-radius: 6px;
      }
    }
  }

  .dialog-footer {
    margin-top: 15px;

    .confirm-btn {
      background: #67c23a;

      &:hover {
        background: #85ce61;
      }
    }
  }
}

/* 水平排列样式（新增） */
.horizontal-payment {
  display: flex;
  gap: 20px;
  /* 选项间距 */
  justify-content: space-between;
}

.payment-option {
  flex: 1;
  /* 等分宽度 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px 0;
  text-align: center;
  transition: all 0.3s;
}

.payment-option:hover {
  border-color: #409EFF;
  background: #f5f7fa;
}

.payment-option.is-checked {
  border-color: #409EFF;
  background: #ecf5ff;
}

/* 保留原有对话框样式 */
.dialog-footer {
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}
</style>
